package com.dwxt.mall.admin.service;


import com.dwxt.common.base.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class FileServiceAdmin {

    @Value("${gate.file.uploadPath}")
    private String uploadPath;

    @Value("${gate.file.realPath}")
    private String realPath;

    @Value("${gate.file.server}")
    private String server;

    public String saveFile(MultipartFile file, String fileName) throws IOException {
        log.info("保存文件开始");
        /**
         * 首先将文件缓存到服务器上
         */
        fileName = createFileName(file.getOriginalFilename(), fileName);
        File dir = new File(realPath + uploadPath);
        if (!dir.exists()) {
            dir.mkdir();
        }
        String savePath = realPath + uploadPath + "/" + fileName;
        File saveFile = new File(savePath);
        file.transferTo(saveFile);
        // 设置访问权限，可读，所有人可读
        saveFile.setReadable(true, false);
        log.info("保存文件结束");
        return server + uploadPath + "/" + fileName;
    }

    /**
     * @方法名：
     * @描述：
     * @作者： lijing
     * @日期： 2018年9月20日
     */
    public String savefile(String base64File) throws IOException {
        log.info("保存文件开始");
        String suffix = "";
        if (base64File.startsWith("data:image/png")) {
            suffix = "png";
            base64File = base64File.replaceAll("data:image/png;base64,", "");
        } else if (base64File.startsWith("data:image/jpeg")) {
            suffix = "jpg";
            base64File = base64File.replaceAll("data:image/jpeg;base64,", "");
        } else if (base64File.startsWith("data:image/jepg")) {
            suffix = "jpg";
            base64File = base64File.replaceAll("data:image/jepg;base64,", "");
        } else if (base64File.startsWith("data:image/jpg")) {
            suffix = "jpg";
            base64File = base64File.replaceAll("data:image/jpg;base64,", "");
        } else if (base64File.startsWith("data:audio/mp3")) {
            suffix = "mp3";
            base64File = base64File.replaceAll("data:audio/mp3;base64,", "");
        }

        byte[] buffer = Base64.decodeBase64(base64File);
        String fileName = createBase64FileName(suffix);
        File dir = new File(realPath + uploadPath);
        if (!dir.exists()) {
            dir.mkdir();
        }
        String savePath = realPath + uploadPath + "/" + fileName;
        FileOutputStream out = new FileOutputStream(savePath);
        out.write(buffer);
        out.close();
        return savePath;
    }


    private String createFileName(String originalFilename, String fileName) {
        String result = "";
        // 获取文件后缀
        String suffix = getFileSuffix(originalFilename);
        if (StringUtils.isNotBlank(fileName)) {
            result = fileName + "." + suffix;
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String date = sdf.format(new Date());
            if (StringUtils.isNotBlank(suffix)) {
                result = date + "." + suffix;
            }
        }
        return result;
    }

    private String createBase64FileName(String suffix) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String date = sdf.format(new Date());
        return date + "." + suffix;
    }

    private String getFileSuffix(String fileName) {
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (StringUtils.isNotBlank(suffix)) {
            suffix = suffix.toLowerCase();
        }
        return suffix;
    }

    /**
     * 保存块文件
     *
     * @param target
     * @param multipartFile
     * @return
     */
    public boolean saveChunkFile(File target, MultipartFile multipartFile) {
        boolean result;
        try {
            FileUtils.writeByteArrayToFile(target, multipartFile.getBytes());
            result = true;
        } catch (IOException e) {
            target.delete();
            result = false;
        }
        return result;
    }
}
